import java.io.IOException;
import java.net.InetSocketAddress;
import java.util.List;

import org.apache.mina.core.future.ConnectFuture;
import org.apache.mina.core.service.IoConnector;
import org.apache.mina.core.service.IoHandlerAdapter;
import org.apache.mina.core.session.IoSession;
import org.apache.mina.filter.codec.ProtocolCodecFilter;
import org.apache.mina.filter.logging.LogLevel;
import org.apache.mina.filter.logging.LoggingFilter;
import org.apache.mina.transport.socket.nio.NioDatagramConnector;

import dictionary.Avp;
import dictionary.RadiusDict;


public class Main {

	public static void main(String[] args) throws IOException {

		//configure client parameters (e.g. which radius server to connect to, path to dictionary file etc.).
		Config cfg = Config.getInstance();
		
		//load radius dictionary
		RadiusDict dict = RadiusDict.getInstance(cfg.getRadiusDictionaryPath());
				
		//parse radius request from file and create RadiusPacket POJO
		TestParser parser = new TestParser();
		RadiusPacket radPacket = parser.parse("D:\\workspace\\radius-trening\\src\\radius_request.txt");
		
		LoggingFilter logFilter = new LoggingFilter();
		logFilter.setMessageReceivedLogLevel(LogLevel.TRACE);
		logFilter.setMessageSentLogLevel(LogLevel.TRACE);
		logFilter.setSessionCreatedLogLevel(LogLevel.TRACE);
		
		IoConnector connector = new NioDatagramConnector();
		//NioDatagramConnector connector = new NioDatagramConnector();
		connector.setConnectTimeoutMillis(5000);
		connector.getFilterChain().addLast("codec", new ProtocolCodecFilter( new RadiusCodecFactory( )));
		connector.getFilterChain().addLast("logging", logFilter);
		connector.setHandler(new Handler1());
		ConnectFuture connFuture = connector.connect(new InetSocketAddress(cfg.getRadiusServerIP(), 1812));
		connFuture.awaitUninterruptibly();
		IoSession session = connFuture.getSession();
		session.write(radPacket);
	}
}

class Handler1 extends IoHandlerAdapter {
	@Override
	public void messageReceived(IoSession session, Object message)
			throws Exception {
		super.messageReceived(session, message);
		Config cfg = Config.getInstance();
		RadiusDict dict = RadiusDict.getInstance(cfg.getRadiusDictionaryPath());
		RadiusPacket pckt = (RadiusPacket) message;
		System.out.println(dict.getCommandName(pckt.getCode()));
		
		List<RadiusAttribute> avpList = pckt.getAvpList();
		
		for (RadiusAttribute attr : avpList) {
			//System.out.println(attr.getLength());
			String avpName = dict.getAvpName(attr.getCode());
			String avpValue = attr.getValueAsString();
			System.out.println(avpName + " = " + avpValue);
		}
		System.exit(0);
	}
	
	@Override
	public void sessionCreated(IoSession session) throws Exception {
		// TODO Auto-generated method stub
		super.sessionCreated(session);
	}
	
	@Override
	public void sessionClosed(IoSession session) throws Exception {
		super.sessionClosed(session);		
	}
}

